package com.cat.twoPointerTechnique;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/description/
 * @create 2025/8/4 10:18
 * @since JDK17
 */

public class Solution11 {
    public int numTriplets(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int ans = 0;
        for (int num : nums1) { //
            ans += f((long)num * num, nums2);
        }
        for (int num : nums2) {
            ans += f((long) num * num, nums1);
        }
        return ans;
    }

    public int f(long target, int[] nums) {
        int ans = 0, n = nums.length, c1, c2;
        for (int l = 0, r = n - 1; l < r; ) {
            long attempt = nums[l] * nums[r];
            if (attempt > target) { // 扩大
                r++;
            } else if (attempt < target) {  // 缩小
                l--;
            } else {    // 两种情况
                if (nums[l] == nums[r]) {   // 全部都一样
                    ans += (r - l + 1) * (r - 1) / 2;
                    break;
                }
                // 判断是否会有一样的情况
                c1 = c2 = 1;
                for (int i = l - 1; i >= 0 && nums[i] == nums[l]; i--, c1++);   // 前面有多少个相同的
                for (int i = r + 1; i < n && nums[i] == nums[r]; i++, c2++);
                ans += c1 * c2;
                l++;
                r--;
            }
        }
        return ans;
    }

}
